前提
操作系统需要安装有Excel
添加Microsoft Excel 16.0 Object Library引用(以系统安装的版本为准)
阅读材料:https://docs.microsoft.com/zh-cn/office/client-developer/excel/excel-home
创建Excel电子表格
类库引用 using Excel = Microsoft.Office.Interop.Excel;
Excel.Application app = new Excel.Application();// 始化Excel应用程序对象
if (app == null) // 检查系统是否已安装Excel
{
MessageBox.Show("Excel未正确安装!");
return;
}
object misValue = System.Reflection.Missing.Value;// 工作簿模板
Excel.Workbook book = app.Workbooks.Add(misValue);// 如果此参数为指定现有 Microsoft Excel 文件名的字符串,那么创建新工作簿将以该指定的文件作为模板。如果此参数为常量,新工作簿将包含一个指定类型的工作表。 可以是以下 XlWBATemplate 常量之一:xlWBATChart、xlWBATExcel4IntlMacroSheet、xlWBATExcel4MacroSheet 或 xlWBATWorksheet。如果省略此参数,Microsoft Excel创建一个包含大量空白工作表的新工作簿(由 SheetsInNewWorkbook 属性设置)
Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets.get_Item(1); // 获取工作表
sheet.Cells[1, 1] = "ID";
sheet.Cells[1, 2] = "Name";
sheet.Cells[2, 1] = "1001";
sheet.Cells[2, 2] = "张三";
sheet.Cells[3, 1] = "1002";
sheet.Cells[3, 2] = "李四";
book.SaveAs("名单表.xls",Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); // 保存电子表格
book.Close(true, misValue, misValue);
app.Quit();
// 资源清理
Marshal.ReleaseComObject(sheet);
Marshal.ReleaseComObject(book);
Marshal.ReleaseComObject(app);
打开Excel电子表格
object misValue = System.Reflection.Missing.Value;
Excel.Application app = new Excel.Application();// 始化Excel应用程序对象
var book = app.Workbooks.Open("名单表.xls", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); // 打开电子表格
var sheet = (Excel.Worksheet)book.Worksheets.get_Item(1);
var cells = sheet.get_Range("A1", "B2").Value; // 获取单元格范围
Console.WriteLine(cells[2, 2]);
book.Close(true, misValue, misValue);
app.Quit();
// 资源清理
Marshal.ReleaseComObject(sheet);
Marshal.ReleaseComObject(book);
Marshal.ReleaseComObject(app);
读取Excel电子表格
object misValue = System.Reflection.Missing.Value;
Excel.Application app = new Excel.Application();// 始化Excel应用程序对象
var book = app.Workbooks.Open(@"名单表.xls", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
var sheet = (Excel.Worksheet)book.Worksheets.get_Item(1);
Excel.Range range = sheet.UsedRange; //指定工作表上的已用区域。 此为只读属性
for (int i = 1; i =0或者 |